<?php

/**
 * Created by PhpStorm.
 * User: 张彪
 * Date: 2016/4/20 0020
 * Time: 下午 3:52
 */
class Article_model  extends Base_Model
{
    public function __construct()
    {
        $this->load->database();
    }

    public function getArices($data = array())
    {
        if (empty($data['id']) || !isset($data['id'])) {


            if (!empty($data['city'])) {
                $this->db->where('m.city', $data['city']);
            }

            if (!empty($data['country'])) {
                $this->db->where('m.country', $data['country']);
            }

            if (!empty($data['start'])) {
                $this->db->where('right(m.freeTimeDays,10)', $data['start']);
            }

            if (!empty($data['end'])) {
                $id = $this->all_track($data['end']);
                if (empty($id)) {
                    $id = array(0);
                }
                $this->db->where_in('m.id', $id);
            }

            if (!empty($data['touristCount'])) {
                $this->db->where('m.serviceMinPersons>=', $data['touristCount']);
            }

            if (!empty($data['people'])) {
                $this->db->where('m.serviceMaxPersons<=', $data['people']);
            }

            if (!empty($data['type'])) {
                $this->db->where('m.uid', 1);
            }

            if (!empty($data['age'])) {
                $this->db->where('u2i.userAge.uid', $data['age'] . '后');
            }

            if (!empty($data['gender'])) {
                $this->db->where('u.userGender', $data['gender']);
            }

            if (!empty($data['identity'])) {
                $this->db->where('u.identityName', $data['identity']);
            }

            if (!empty($data['language'])) {
                $key = 'cn';
                if ($data['language'] == 1) {
                    $key = 'cn';
                } else if ($data['language'] == 2) {
                    $key = 'fr';
                } else if ($data['language'] == 3) {
                    $key = 'en';
                }

                $this->db->where('u.' . $key, 1);
            }
            if (!empty($data['id'])) {
                $this->db->where('m.id', $data['id']);
            }
            if (!empty($data['guiderUid'])) {
                $this->db->where('m.uid', $data['guiderUid']);
            }
            $this->db->where('m.status', 'VALID');

            $this->db->join('user_v2 as u', 'u.uid = m.uid', 'left');
            $this->db->join('user_v2_userinfo as u2i', 'u2i.uid = m.uid', 'left');
            $count = $this->db->count_all_results('mod_activity as m');

        }


        if (!empty($data['city'])) {
            $this->db->where('m.city', $data['city']);
        }

        if (!empty($data['country'])) {
            $this->db->where('m.country', $data['country']);
        }

        if (!empty($data['start'])) {
            $this->db->where('right(m.freeTimeDays,10)', $data['start']);
        }


        if (!empty($data['end'])) {
            $id = $this->all_track($data['end']);
            if (empty($id)) {
                $id = array(0);
            }
            $this->db->where_in('m.id', $id);
        }

        if (!empty($data['touristCount'])) {
            $this->db->where('m.serviceMinPersons>=', $data['touristCount']);
        }

        if (!empty($data['people'])) {
            $this->db->where('m.serviceMaxPersons<=', $data['people']);
        }

        if (!empty($data['type'])) {
//            $this->db->where('m.uid', 1);
        }

        if (!empty($data['age'])) {
            $this->db->where('u2i.userAge.uid', $data['age'] . '后');
        }

        if (!empty($data['gender'])) {
            $this->db->where('u.userGender', $data['gender']);
        }

        if (!empty($data['identity'])) {
            $this->db->where('u.identityName', $data['identity']);
        }

        if (!empty($data['language'])) {
            $key = 'cn';
            if ($data['language'] == 1) {
                $key = 'cn';
            } else if ($data['language'] == 2) {
                $key = 'fr';
            } else if ($data['language'] == 3) {
                $key = 'en';
            }

            $this->db->where('u.' . $key, 1);
        }
        if (!empty($data['id'])) {
            $this->db->where('m.id', $data['id']);
        }
        if (!empty($data['guiderUid'])) {
            $this->db->where('m.uid', $data['guiderUid']);
        }
        $this->db->where('m.status', 'VALID');
        if (!empty($data['$offset']) && !empty($data['limit'])) {
            $this->db->limit($data['$offset'], $data['limit']);
        }
        $this->db->from('mod_activity as m');
        $this->db->join('user_v2 as u', 'u.uid = m.uid', 'left');
        $this->db->join('user_v2_userinfo as u2i', 'u2i.uid = m.uid', 'left');
        $query = $this->db->get()->result_array();

        if (!empty($data['id'])) {
            $re = $query;
        } else {
            $re['count'] = $count;
            $items = array();
            foreach ($query as $v) {
//                $items['name'] = $v['name'];
//                $items['orders'] = $v['orders'];
//                $items['thumb'] = $v['thumb'];
//                $items['summary'] = $v['summary'];
//                $items[''] = $v[''];
//                $items[''] = $v[''];
//                $items[''] = $v[''];

            }

            $re['articles'] = $query;


        }
        var_dump($re);
        die;
        return $re;
    }

    public function get_track_and_act($data = array())
    {
        $Where = '';
        if (!empty($data['guiderUid'])) {
            $Where .= ' AND uid =' . $data['guiderUid'];
        }

        if(!empty($data['cityId']))
        {
            $Where .= ' AND cityId =' . $data['cityId'];
        }
        $sql = '';
        if (!empty($data['sortkey'])) {
            $sorttype = empty($data['sorttype']) ? 'DESC' : $data['sorttype'];
            $sql = " ORDER BY {$data['sortkey']} {$sorttype}";
        }

        if (!empty($data['limit'])) {
            $offset = empty($data['offset']) ? "0" : $data['offset'];
            $sql .= "	LIMIT {$data['limit']} OFFSET {$offset}";
        }

        $sql1 = 'SELECT
                    `uid`,
                    `id`,
                    `city`,
                    `name`,
                    `thumb`,
                    `summary`,
                    `priceTotal`,
                    `changed`,
                    `created`,
                    `type`,
                    `zan`
                FROM
                    `mod_track`
                WHERE
                    `status` = \'VALID\' ' . $Where;
        $sql2 = 'SELECT
                    `uid`,
                    `id`,
                    `city`,
                    `name`,
                    `thumb`,
                    `summary`,
                    `priceTotal`,
                    `changed`,
                    `created`,
                    `type`,
                    `zan`
                FROM
                    `mod_activity`
                WHERE
                    `status` = \'VALID\' ' . $Where;
        $query = $this->db->query($sql1 . ' UNION ALL ' . $sql2 . $sql);

        $items = array();
        foreach ($query->result_array() as $rs) {
            $item = array();
//            var_dump($rs);die;
//            $item['guider'] = $this->getUserInfoById($rs['uid']);
            $guider = $this->getUserInfoById($rs['uid']);
            $this->getUserInfoById($rs['uid']);
            $item['type'] = strtolower($rs['type']);
            $item['id'] = $rs['id'];
            $item['thumb'] = $this->img($rs['thumb']);;
            $item['name'] = $rs['name'];
            $item['city'] = $rs['city'];
            $item['price'] = round($rs['priceTotal'] / 100, 2) . '€';
            $item['summary'] = $rs['summary'];
            $item['userIcon'] = $this->img($guider['userIcon']);
//            empty($guider['userIcon'])?'':$guider['userIcon'];
            $item['realName'] = empty($guider['realName']) ? '' : $guider['realName'];
            $items[] = $item;
        }
        return $items;
    }



    /**
     * 搜索线路
     */
    public function track_act_search($data = array())
    {
        $w_sql1 = '';
        $w_sql2 = '';
        if (!empty($data['type'])) {
            $tr = $this->getTracks($data['type']);
            if(!empty($tr))
            {
                $trackIds = implode(',', $tr);
//                if(count($tr) ==1)
//                {
//                    $w_sql1 .= " AND m.id = $trackIds";
//                    $w_sql2 .= " AND a.id = $trackIds";
//                }else{

                    $w_sql1 .= " AND m.id in ($trackIds)";
//                }

            }
            $acts = $this->getTracks($data['type'],'ACTIVITY');
            if(!empty($acts))
            {
                $acts = implode(',', $acts);

                $w_sql2 .= " AND a.id in ($acts)";
            }

        }

        if (!empty($data['city'])) {
            $w_sql1 .= " AND m.cityId = {$data['city']} ";
            $w_sql2 .= " AND a.cityId = {$data['city']} ";
        }

        if (!empty($data['start'])) {
            $id_start_m = $this->get_line_with_start($data['start'], 'mod_track');
            if (!empty($id_start_m)) {
                $id_start_m = implode(',', $id_start_m);
//                if(count($id_start_m) == 1)
//                {
//                    $w_sql1 .= " AND m.id = $id_start_m";
//                    $w_sql2 .= " AND a.id = $id_start_m";
//                }else{
                    $w_sql1 .= " AND m.id in ($id_start_m)";
                    $w_sql2 .= " AND a.id in ($id_start_m)";
//                }

            }


        }

        if (!empty($data['end'])) {

            $id_end_m = $this->get_line_with_end($data['end'], 'mod_track');
            if (!empty($id_end_m)) {
                $id_end_m = implode(',', $id_end_m);
//                if(count($id_end_m) == 1)
//                {
//                    $w_sql1 .= " AND m.id = $id_end_m";
//                    $w_sql2 .= " AND a.id = $id_end_m";
//                }else{
                    $w_sql1 .= " AND m.id in ($id_end_m)";
                    $w_sql2 .= " AND a.id in ($id_end_m)";
//                }
            }
        }

        if(!empty($data['number']))
        {
            $w_sql1 .= " AND m.serviceMinPersons >= '{$data['number']}'";
            $w_sql2 .= " AND a.serviceMinPersons >= '{$data['number']}'";
        }

        if(!empty($data['age']))
        {
            $w_sql1 .= " AND u2i.userAge >= {$data['age']}后";
            $w_sql2 .= " AND u2i.userAge >= {$data['age']}后";
        }

        if(!empty($data['gender']))
        {
            $w_sql1 .= " AND u.userGender = {$data['gender']}";
            $w_sql2 .= " AND u.userGender = {$data['gender']}";
        }

        if(!empty($data['identity']))
        {
            $w_sql1 .= " AND u.identityName = {$data['identity']}";
            $w_sql2 .= " AND u.identityName = {$data['identity']}";
        }

        if(!empty($data['$language']))
        {
            if($data['$language'] == 1){
                $lkey = 'cn';
                $w_sql1 .= " AND u.{$lkey} = 1";
                $w_sql2 .= " AND u.{$lkey} = 1";
            }else if($data['$language'] == 2){
                $lkey = 'fr';
                $w_sql1 .= " AND u.{$lkey} = 1";
                $w_sql2 .= " AND u.{$lkey} = 1";
            }else if($data['$language'] == 3){
                $lkey = 'en';
                $w_sql1 .= " AND u.{$lkey} = 1";
                $w_sql2 .= " AND u.{$lkey} = 1";
            }


        }

        if(!empty($data['chuxing']))
        {
            if($data['chuxing']==1){
                $w_sql1 .= " AND m.trafficSupportCar = 1";
                $w_sql2 .= " AND a.trafficSupportCar = 1";
            }elseif($data['chuxing']==2){
                $w_sql1 .= " AND m.trafficSupportBus = 1";
                $w_sql2 .= " AND m.trafficSupportBus = 1";
            }
        }

        $sql = '';
        $orderSql = array();
        if (!empty($data['limit'])) {
            $offset = empty($data['offset']) ? "0" : $data['offset'];
            $sql .= "	LIMIT {$data['limit']} OFFSET {$offset}";
        }
        if(!empty($data['price']))
        {
            if($data['price'] == 2)
            {
                $orderSql[]= "	 priceTotal asc";
            }elseif ($data['price'] == 1)
            {
                $orderSql[]= "	 priceTotal desc";
            }
        }


        if(!empty($data['order']))
        {
            if($data['order'] == 2 ){
                $orderSql[]= "	 orders asc";
            }else if($data['order'] == 1 ){
                $orderSql[]= "	 orders desc";
            }
        }

        if(!empty($data['score']))
        {
            if($data['score'] == 2 ){
                $orderSql[]= "	 score asc";
            }else if($data['score'] == 1 ){
                $orderSql[]= "	 score desc";
            }
        }

        if(!empty($orderSql))
        {
            $order = implode(',',$orderSql);
            $sql = 'ORDER BY '.$order;
        }

//        if (!empty($data['limit'])) {
//            $offset = empty($data['offset']) ? "0" : $data['offset'];
//            $sql .= "	LIMIT {$data['limit']} OFFSET {$offset}";
//        }

        $sql1 = "SELECT
                    `a`.`uid`,
                    `a`.`id`,
                    `a`.`city`,
                    `a`.`cityId`,
                    `a`.`name`,
                    `a`.`thumb`,
                    `a`.`summary`,
                    `a`.`priceTotal`,
                    `a`.`hours` AS `duration`,
                    `a`.`score`,
                    `a`.`changed`,
                    `a`.`type`,
                    `a`.`zan`,
                    `a`.`serviceMaxPersons`,
                    `a`.`orders`,
                    `a`.`trafficSupportCar`,
                    `a`.`trafficSupportBus`,
                    `u`.`userName`,
                    `u2i`.`userIcon`,
                    `u`.`identityActive`,
                    `u`.`telActive`,
                    `u2i`.`userAge`,
                    `u2i`.`userGender`,
                    `u`.`identityName`,
                    `u`.`cn`,
                    `u`.`en`,
                    `u`.`fr`
                FROM
                    `mod_activity` AS `a`
                LEFT JOIN `user_v2` AS `u` ON (`a`.`uid` = `u`.`uid`)
                LEFT JOIN `user_v2_userinfo` AS `u2i` ON (`u`.`uid` = `u2i`.`uid`)
                WHERE
                    `a`.`status` = 'VALID' {$w_sql2}
                ";

        $sql2 = "SELECT
                    `m`.`uid`,
                    `m`.`id`,
                    `m`.`city`,
                    `m`.`cityId`,
                    `m`.`name`,
                    `m`.`thumb`,
                    `m`.`summary`,
                    `m`.`priceTotal`,
                    `m`.`days` AS `duration`,
                    `m`.`score`,
                    `m`.`changed`,
                    `m`.`type`,
                    `m`.`zan`,
                    `m`.`serviceMaxPersons`,
                    `m`.`orders`,
                    `m`.`trafficSupportCar`,
                    `m`.`trafficSupportBus`,
                    `u`.`userName`,
                    `u2i`.`userIcon`,
                    `u`.`identityActive`,
                    `u`.`telActive`,
                    `u2i`.`userAge`,
                    `u2i`.`userGender`,
                    `u`.`identityName`,
                    `u`.`cn`,
                    `u`.`en`,
                    `u`.`fr`
                FROM
                    `mod_track` AS `m`
                LEFT JOIN `user_v2` AS `u` ON (`m`.`uid` = `u`.`uid`)
                LEFT JOIN `user_v2_userinfo` AS `u2i` ON (`u`.`uid` = `u2i`.`uid`)
                WHERE
                    `m`.`status` = 'VALID' $w_sql1
                 ";

        $query = $this->db->query($sql1 . ' UNION ALL ' . $sql2 . $sql);
        $line = $query->result_array();
        $items = array();
        if(!empty($line))
        {
            foreach ($line as $q)
            {
                $item = array();
                $item['score'] = $q['score'];
                $item['type'] = $q['type'];
                $item['id'] = $q['id'];
                $item['thumb'] = $this->img($q['thumb']);
                $item['name'] = $q['name'];
                $item['userIcon'] = $this->img($q['userIcon']);
                $item['userName'] = $q['userName'];
                $item['identityActive'] = $q['identityActive'];
                $item['telActive'] = $q['telActive'];
                $item['userAge'] = $q['userAge'];
                $item['userGender'] = $q['userGender'];
                $item['identityName'] = $q['identityName'];
                $item['cn'] = $q['cn'];
                $item['en'] = $q['en'];
                $item['fr'] = $q['fr'];
                $item['summary'] = nl2br($q['summary']);
                $item['price'] = round($q['priceTotal']/100*1.1,2);
                $item['duration'] = $q['duration'];
                $item['duration'] = $q['duration'];
                $item['serviceMaxPersons'] = $q['serviceMaxPersons'];
                $item['trafficSupportCar'] = $q['trafficSupportCar'];
                $item['orders'] = $q['orders'];
                $items[] = $item;
            }

        }


        return $items;

    }


    public function all_track($date = null)
    {
        $query = $this->db->query("select id ,freetimeDays from mod_activity   WHERE status = VALID");
        $data = $query->result_array();
        $id = array();
        $time = strtotime($date);
        foreach ($data as $v) {
            $days = explode(',', $v['freetimeDays']);
            foreach ($days as $day) {
                $day_time = strtotime($day);
                if ($time > $day_time) {
                    $id[] = "'".$v['id']."'";
                    break;
                }
            }
        }

        return $id;

    }


    public function get_line_with_start($date = NULL, $table)
    {
        $query = $this->db->query("select id ,freetimeDays from {$table}   WHERE status = VALID");
        $data = $query->result_array();

        $id = array();
        $time = strtotime($date);
        foreach ($data as $v) {
            $days = explode(',', $v['freetimeDays']);
            foreach ($days as $day) {
                $day_time = strtotime($day);
                if ($time < $day_time || $time == $day_time) {
                    $id[] = "'".$v['id']."'";
                    break;
                }
            }
        }
        return $id;
    }

    public function get_line_with_end($date = NULL, $table)
    {
        $query = $this->db->query("select id ,freetimeDays from {$table}   WHERE status = VALID");
        $data = $query->result_array();
        $id = array();
        $time = strtotime($date);
        foreach($data as $v){
            $days = explode(',',$v['freetimeDays']);
            foreach($days as $day){
                $day_time = strtotime($day);
                if($time > $day_time||$time==$day_time){
                    $id[] = "'".$v['id']."'";
                    break;
                }
            }
        }

        return $id;
    }



    public function getTracks($type,$targetType='TRACK')
    {
        $query  = $this->db->query("select targetNid from tiyu_categorygl   WHERE targetType = '{$targetType}'  AND categoryId = {$type}");
        $data = $query->result_array();
        $trackIds = array();
        if(!empty($data)) {
            foreach ($data as $t) {
                $trackIds[] = "'".$t['targetNid']."'";
            }

        }
        return $trackIds;
    }


    /**
     * @param $id
     * @return mixed
     * 获取单个详情
     */
    public function detail($id)
    {

        $this->db->where('id', $id);
        $this->db->from('mod_activity ');
        $query = $this->db->get()->row_array();

        if(!empty($query['uid']))
        {
            $guider = $this->getUserInfoById($query['uid']);
        }else{
            return false;
        }
        $Imgs = explode('|',$query['images']);
        if(!empty($Imgs))
        {
            foreach ($Imgs as $k=>$img)
            {
                $Img[$k] = $this->img($img);
            }

        }

        $item['name'] = $query['name'];
        $item['userIcon'] = $this->img($guider['userIcon']);
        $item['realName'] = $guider['realName'];
        $item['identityActive'] = $guider['identityActive'];
        $item['telActive'] = $guider['telActive'];
        $item['resideCity'] = $guider['resideCity'];
        $item['resideTime'] = $guider['resideTime'];
        $item['userAge'] = $guider['userAge'];
        $item['userGender'] = $guider['userGender'];
        $item['identityName'] = $guider['identityName'];
        $item['identityErea_zhuanye'] = $guider['identityErea_zhuanye'];
        $item['identityErea_school'] = $guider['identityErea_school'];
        $item['introduction'] = nl2br($guider['introduction']);
        $item['hours'] = $query['hours'];
        $item['serviceMaxPersons'] = $query['serviceMaxPersons'];
        $item['location'] = $query['location'];
        $item['summary'] = nl2br($query['summary']);
        $item['todolist'] = nl2br($query['todolist']);
        $item['images'] = $Imgs;
//        $item['price'] = ($query['descService']/100)."€";
        $item['priceService'] = $query['priceService'];
        $item['descService'] = $query['descService'];
        $item['descService'] = nl2br($query['descService']);
        $item['name'] = $query['name'];
        $item['name'] = $query['name'];
        $item['todolist'] = $query['todolist'];
        return $item;
//        var_dump($item);die;

    }
    public function getbyid($id)
    {
        $this->db->where('id', $id);
        $this->db->from('mod_activity');
        $query = $this->db->get()->row_array();
        return $query;
    }

}